package top.codedance.iotp.common.executer;

import cd.io.netty.channel.ChannelHandlerContext;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.entity.CommonEntity;
import top.codedance.iotp.common.entity.PluginResultEntity;
import org.ini4j.Wini;

import java.nio.charset.StandardCharsets;

public abstract class AsyncAbstractExecuter implements CommonClientPluginExecuter {

    protected ChannelHandlerContext channelHandlerContext;
    protected Wini ini;
    protected CommonEntity commonEntity;
    protected String taskId;
    private JSONObject requestBodyJSONObject;
    private String clientId;
    private int instance;
    private String deviceId;

    @Override
    public void setIniConfig(Wini ini) {
        this.ini = ini;
    }

    @Override
    public Wini getIniConfig() {
        return this.ini;
    }

    /**
     * 空实现同步执行的接口
     * @param data
     * @param taskId
     * @return
     */
    @Override
    public PluginResultEntity exec(byte[] data, String taskId){
        return new PluginResultEntity();
    }

    @Override
    public void exec(ChannelHandlerContext channelHandlerContext, CommonEntity commonEntity, String taskId) {
        this.channelHandlerContext = channelHandlerContext;
        this.commonEntity = commonEntity;
        this.taskId = taskId;
        String s = new String(commonEntity.getBody(), StandardCharsets.UTF_8);
        requestBodyJSONObject = JSONObject.parseObject(s);
        clientId = requestBodyJSONObject.getString("clientId");
        instance = requestBodyJSONObject.getInteger("instance");
        deviceId = requestBodyJSONObject.getString("deviceId");
    }

    public void send(CommonEntity newCommonEntity){
        send(newCommonEntity, null);
    }

    public synchronized void send(CommonEntity newCommonEntity, String cid){
        newCommonEntity.setVersion(commonEntity.getVersion());
        String ns = new String(newCommonEntity.getBody(), StandardCharsets.UTF_8);
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("data", ns);
        jsonObject2.put("clientId", cid == null ? clientId : cid);
        jsonObject2.put("instance", instance);
        jsonObject2.put("deviceId", deviceId);
        newCommonEntity.setBody(jsonObject2.toJSONString().getBytes(StandardCharsets.UTF_8));
        channelHandlerContext.writeAndFlush(newCommonEntity.build());
    }

    public JSONObject getRequestBodyJSONObject(){
        return requestBodyJSONObject;
    }

    public String getClientId(){
        return clientId;
    }

    public int getInstance() {
        return instance;
    }
}
